package com.pic.mgt.haishin.executer;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.time.DateUtils;

import com.pic.mgt.haishin.AppointedHaishinRuleConfig;
import com.pic.mgt.haishin.AppointedHaishinSizePattern;
import com.pic.mgt.manager.terminal.BasicTerminalInfoBean;
import com.pic.mgt.utils.DateConvertUtils;

public class DistributedExecutionTimeAsgmtFileProcess extends AsgmtFileProcess {
	private AppointedHaishinRuleConfig appointedHaishinRuleConfig;
	
	private int currentDivideAmount;
	private int clientDivideAmount;
	private int expectedDLTime;
	private Date currentExecutionTime;
	
	public DistributedExecutionTimeAsgmtFileProcess(
			AppointedHaishinRuleConfig appointedHaishinRuleConfig) {
		super();
		
		this.appointedHaishinRuleConfig = appointedHaishinRuleConfig;
		
		clientDivideAmount = this.appointedHaishinRuleConfig.
											getClientDivideAmount();
	}

	// 針對每一項業務(Business)，在做建立確認檔時,初始化方法都會先被呼叫一次
	@Override
	void initial()  throws AsgmtFileProcessInitialException {
		this.currentDivideAmount = -1;
		this.expectedDLTime = -1;
		
		List<AppointedHaishinSizePattern> appointedHaishinSizePattern =
			this.appointedHaishinRuleConfig.getAppointedHaishinPatternList();
		for(AppointedHaishinSizePattern pattern : appointedHaishinSizePattern) {
			if ((super.targetFilesize > pattern.getLowerBound() && 
					super.targetFilesize <= pattern.getUpperBound())){
				this.expectedDLTime = pattern.getExpectedDLTime();
			}
		}
		if (this.expectedDLTime == -1) {
			throw new AsgmtFileProcessInitialException(
					"Can't find matched pattern for target filesize '" +
					super.targetFilesize + "'");
		}
	}
	
	@Override
	String getSpecificExecutionTimeContentInAsgmtFile(Date initialExecutionTime, BasicTerminalInfoBean basicTerminalInfoBean) {
		if (this.currentDivideAmount == -1) {
			// currentDivideAmount 為 -1，表示做過初始化動作
			this.currentExecutionTime = initialExecutionTime;
			this.currentDivideAmount++;
		}
		
		this.currentDivideAmount++;
		
		if (this.currentDivideAmount > this.clientDivideAmount) {
			this.currentExecutionTime = DateUtils.addMinutes(
					this.currentExecutionTime, this.expectedDLTime);
			this.currentDivideAmount = 1;
		}
		
		// <<2011/10/20 指示檔內容時間格式變更 by Timothy>>
		String dateString = DateConvertUtils.
						dateToyyyyMMddHHmmString(this.currentExecutionTime);
		return dateString;
	}
}
